package com.yj.springbootstudy.mulThread.imooc.juctools;

import java.util.Random;
import java.util.concurrent.CopyOnWriteArrayList;

public class CopyOnWriteArrayListTest {

    private static CopyOnWriteArrayList<String> list = new CopyOnWriteArrayList<>();

    static {
        list.add("ipAddr0");
        list.add("ipAddr1");
        list.add("ipAddr2");
    }

    public static void main(String[] args) {
        Runnable runnable = ()->{
            // 模拟接入用时
            try {
                Thread.sleep(new Random().nextInt(5000));

                String currentIp = "ipAddr"+new Random().nextInt(5);

                if (list.contains(currentIp)){
                    System.out.println(Thread.currentThread().getName() + "IP" + currentIp + "命中黑名单，拒绝接入操作！");
                    return;
                }
                System.out.println(Thread.currentThread().getName() + "IP" + currentIp + "接入处理，执行下面的逻辑！");
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        };
        new Thread(runnable,"t1").start();
        new Thread(runnable,"t2").start();
        new Thread(runnable,"t3").start();

        new Thread(()->{
            // 模拟用时
            try {
                Thread.sleep(new Random().nextInt(2000));
                String newBlackIp = "ipAddr3";
                list.add(newBlackIp);
                System.out.println(Thread.currentThread().getName() + "添加了新的非法IP"+newBlackIp);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        },"更新黑名单").start();
    }
}
